"""
扫货脚本管理页面
"""
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget,
                           QTableWidgetItem, QPushButton, QLineEdit, QLabel,
                           QHeaderView, QFrame, QMessageBox)
from PyQt6.QtCore import Qt, QTimer, pyqtSignal, QMetaObject
from PyQt6.QtGui import QColor
from com.db.script_manager import ScriptManager
from com.db.script_task_manager import ScriptTaskManager
from com.db.script_scan_account_manager import ScriptScanAccountManager
from gui.styles.table_style import apply_default_table_style, set_columns_stretch
from gui.styles.pagination_style import PaginationWidget
from gui.widgets.script_dialog import ScriptDialog
from gui.widgets.log_window import LogWindow
from gui.widgets.scan_mode_dialog import ScanModeDialog
from biz.script_task_processor import ScriptTaskProcessor, ScanMode
from biz.script_runner import get_script_runner
import threading

class ScriptPage(QWidget):
    """扫货脚本管理页面"""
    
    # 定义信号
    script_stopped = pyqtSignal(int)  # 脚本停止信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.script_manager = ScriptManager()
        self.script_task_manager = ScriptTaskManager()
        self.script_scan_account_manager = ScriptScanAccountManager()
        self.running_scripts = set()  # 记录正在运行的脚本ID
        self.script_processors = {}  # 记录脚本处理器实例
        self.log_windows = {}  # 记录日志窗口实例
        
        # 连接信号
        self.script_stopped.connect(self._handle_script_stop)
        
        self.setup_ui()
        self.load_scripts()  # 从数据库加载脚本数据
        
        # 移除自动刷新定时器
        # self.refresh_timer = QTimer(self)
        # self.refresh_timer.timeout.connect(self.load_scripts)
        # self.refresh_timer.start(30000)  # 30秒
    
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)  # 移除边距，使表格占满整个空间
        layout.setSpacing(0)  # 减少间距
        
        # 搜索区域
        search_frame = QFrame()
        search_frame.setStyleSheet("""
            QFrame {
                background-color: white;
                border: none;
                border-bottom: 1px solid #ebeef5;
            }
        """)
        search_layout = QHBoxLayout(search_frame)
        search_layout.setContentsMargins(15, 10, 15, 10)
        
        # 左侧搜索区域
        left_widget = QWidget()
        left_layout = QHBoxLayout(left_widget)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(10)
        
        # 右侧按钮区域
        right_widget = QWidget()
        right_layout = QHBoxLayout(right_widget)
        right_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setSpacing(10)
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新")
        refresh_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        refresh_btn.clicked.connect(self.refresh_table)
        right_layout.addWidget(refresh_btn)
        
        # 添加按钮
        add_btn = QPushButton("添加")
        add_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #67c23a;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #85ce61;
            }
        """)
        add_btn.clicked.connect(self.on_add_script)
        right_layout.addWidget(add_btn)
        
        # 将左右两侧添加到主布局
        search_layout.addWidget(left_widget)
        search_layout.addStretch()
        search_layout.addWidget(right_widget)
        
        # 表格
        self.script_table = QTableWidget()
        apply_default_table_style(self.script_table)
        
        # 设置表格列
        headers = ["脚本名称", "自动报价", "任务数量", "自动任务", "自动任务", "执行状态", "扫货节点", "操作"]
        self.script_table.setColumnCount(len(headers))
        self.script_table.setHorizontalHeaderLabels(headers)
        
        # 设置表格列宽
        set_columns_stretch(self.script_table)
        
        # 分页控件
        self.pagination = PaginationWidget()
        self.pagination.prev_btn.clicked.connect(self.on_prev_page)
        self.pagination.next_btn.clicked.connect(self.on_next_page)
        self.pagination.page_size_spin.valueChanged.connect(self.on_page_size_changed)
        
        # 添加到主布局
        layout.addWidget(search_frame)
        layout.addWidget(self.script_table)
        layout.addWidget(self.pagination)
    
    def load_scripts(self, keyword=None):
        """从数据库加载脚本数据"""
        # 获取当前页数据
        page = self.pagination.page
        page_size = self.pagination.page_size
        offset = (page - 1) * page_size

        print(f"加载脚本数据: 页码={page}, 每页数量={page_size}, 偏移={offset}, 关键字={keyword}")

        # 获取总记录数和记录
        total_count = self.script_manager.get_script_count(keyword)
        print(f"总记录数: {total_count}")
        
        # 获取分页数据
        scripts = self.script_manager.search_scripts(
            keyword=keyword,
            limit=page_size,
            offset=offset
        ) if keyword else self.script_manager.get_all_scripts(
            limit=page_size,
            offset=offset
        )
        print(f"获取到{len(scripts)}条记录")
        
        # 更新分页状态
        self.pagination.update_state(page, total_count, page_size)
        
        # 更新表格
        self.script_table.setRowCount(len(scripts))
        
        # 状态映射
        status_map = {0: "禁用", 1: "启用"}
        run_status_map = {0: "停止", 1: "运行中"}
        
        for row, script in enumerate(scripts):
            script_id = script.get('id')  # 获取脚本ID
            
            # 脚本名称
            self.script_table.setItem(row, 0, QTableWidgetItem(str(script.get('name', ''))))
            # 自动报价
            self.script_table.setItem(row, 1, QTableWidgetItem("是" if script.get('is_auto_offer') else "否"))
            # 任务数量
            self.script_table.setItem(row, 2, QTableWidgetItem(str(script.get('task_count', 0))))
            # 自动任务
            self.script_table.setItem(row, 3, QTableWidgetItem(status_map.get(script.get('status', 0), "未知")))
            # 自动任务
            self.script_table.setItem(row, 4, QTableWidgetItem(status_map.get(script.get('status', 0), "未知")))
            # 执行状态
            self.script_table.setItem(row, 5, QTableWidgetItem(run_status_map.get(script.get('run_status', 0), "未知")))
            # 扫货节点
            self.script_table.setItem(row, 6, QTableWidgetItem("主节点" if script.get('node_index') == 1 else "备用节点"))
            
            # 操作按钮容器
            btn_widget = QWidget()
            btn_layout = QHBoxLayout(btn_widget)
            btn_layout.setSpacing(5)
            btn_layout.setContentsMargins(0, 0, 0, 0)
            
            # 编辑按钮
            edit_btn = QPushButton("编辑")
            edit_btn.setStyleSheet("""
                QPushButton {
                    padding: 3px 8px;
                    background-color: #409eff;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                }
                QPushButton:hover {
                    background-color: #66b1ff;
                }
            """)
            # 保存脚本ID到按钮的属性中
            edit_btn.setProperty('script_id', script_id)
            edit_btn.clicked.connect(self.on_edit_script)
            
            # 启动按钮
            start_btn = QPushButton("启动" if script_id not in self.running_scripts else "停止")
            start_btn.setStyleSheet("""
                QPushButton {
                    padding: 3px 8px;
                    background-color: """ + ("#f56c6c" if script_id in self.running_scripts else "#67c23a") + """;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                }
                QPushButton:hover {
                    background-color: """ + ("#f78989" if script_id in self.running_scripts else "#85ce61") + """;
                }
            """)
            start_btn.setProperty('script_id', script_id)
            start_btn.clicked.connect(self.on_start_script)
            
            # 扫货日志按钮
            log_btn = QPushButton("扫货日志")
            log_btn.setStyleSheet("""
                QPushButton {
                    padding: 3px 8px;
                    background-color: #909399;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                }
                QPushButton:hover {
                    background-color: #a6a9ad;
                }
            """)
            log_btn.setProperty('script_id', script_id)
            log_btn.clicked.connect(self.on_view_scan_log)
            
            # 删除按钮
            delete_btn = QPushButton("删除")
            delete_btn.setStyleSheet("""
                QPushButton {
                    padding: 3px 8px;
                    background-color: #f56c6c;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                }
                QPushButton:hover {
                    background-color: #f78989;
                }
            """)
            delete_btn.setProperty('script_id', script_id)
            delete_btn.clicked.connect(self.on_delete_script)
            
            # 添加按钮到布局
            btn_layout.addWidget(edit_btn)
            btn_layout.addWidget(start_btn)
            btn_layout.addWidget(log_btn)
            btn_layout.addWidget(delete_btn)
            btn_layout.addStretch()
            
            # 设置单元格的小部件
            self.script_table.setCellWidget(row, 7, btn_widget)
            
        print("表格更新完成")

    def on_prev_page(self):
        """上一页"""
        if self.pagination.page > 1:
            self.pagination.page -= 1
            self.load_scripts()
    
    def on_next_page(self):
        """下一页"""
        self.pagination.page += 1
        self.load_scripts()
    
    def on_page_size_changed(self, value):
        """每页数量改变事件"""
        self.pagination.page_size = value
        self.pagination.page = 1
        self.load_scripts()
        
    def on_add_script(self):
        """打开添加脚本对话框"""
        dialog = ScriptDialog(parent=self)
        dialog.exec()
        
    def refresh_table(self):
        """刷新表格数据"""
        # 获取当前页码和每页大小
        page = self.pagination.page
        page_size = self.pagination.page_size
        offset = (page - 1) * page_size
        
        # 获取总记录数和记录
        total_count = self.script_manager.get_script_count()
        print(f"总记录数: {total_count}")
        
        # 获取分页数据
        scripts = self.script_manager.get_all_scripts(
            limit=page_size,
            offset=offset
        )
        print(f"获取到{len(scripts)}条记录")
        
        # 更新分页状态
        self.pagination.update_state(page, total_count, page_size)
        
        # 更新表格
        self.script_table.setRowCount(len(scripts))
        
        # 状态映射
        status_map = {0: "禁用", 1: "启用"}
        run_status_map = {0: "停止", 1: "运行中"}
        
        for row, script in enumerate(scripts):
            script_id = script.get('id')  # 获取脚本ID
            
            # 脚本名称
            self.script_table.setItem(row, 0, QTableWidgetItem(str(script.get('name', ''))))
            # 自动报价
            self.script_table.setItem(row, 1, QTableWidgetItem("是" if script.get('is_auto_offer') else "否"))
            # 任务数量
            self.script_table.setItem(row, 2, QTableWidgetItem(str(script.get('task_count', 0))))
            # 自动任务
            self.script_table.setItem(row, 3, QTableWidgetItem(status_map.get(script.get('status', 0), "未知")))
            # 自动任务
            self.script_table.setItem(row, 4, QTableWidgetItem(status_map.get(script.get('status', 0), "未知")))
            # 执行状态
            self.script_table.setItem(row, 5, QTableWidgetItem(run_status_map.get(script.get('run_status', 0), "未知")))
            # 扫货节点
            self.script_table.setItem(row, 6, QTableWidgetItem("主节点" if script.get('node_index') == 1 else "备用节点"))
            
            # 操作按钮容器
            btn_widget = QWidget()
            btn_layout = QHBoxLayout(btn_widget)
            btn_layout.setSpacing(5)
            btn_layout.setContentsMargins(0, 0, 0, 0)
            
            # 编辑按钮
            edit_btn = QPushButton("编辑")
            edit_btn.setStyleSheet("""
                QPushButton {
                    padding: 3px 8px;
                    background-color: #409eff;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                }
                QPushButton:hover {
                    background-color: #66b1ff;
                }
            """)
            # 保存脚本ID到按钮的属性中
            edit_btn.setProperty('script_id', script_id)
            edit_btn.clicked.connect(self.on_edit_script)
            
            # 启动/停止按钮
            start_btn = QPushButton("停止" if script_id in self.running_scripts else "启动")
            start_btn.setStyleSheet("""
                QPushButton {
                    padding: 3px 8px;
                    background-color: """ + ("#f56c6c" if script_id in self.running_scripts else "#67c23a") + """;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                }
                QPushButton:hover {
                    background-color: """ + ("#f78989" if script_id in self.running_scripts else "#85ce61") + """;
                }
            """)
            start_btn.setProperty('script_id', script_id)
            start_btn.setProperty('run_status', 0)  # 保存当前运行状态到按钮属性中
            start_btn.clicked.connect(self.on_start_script)
            
            # 扫货日志按钮
            log_btn = QPushButton("扫货日志")
            log_btn.setStyleSheet("""
                QPushButton {
                    padding: 3px 8px;
                    background-color: #909399;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                }
                QPushButton:hover {
                    background-color: #a6a9ad;
                }
            """)
            log_btn.setProperty('script_id', script_id)
            log_btn.clicked.connect(self.on_view_scan_log)
            
            # 删除按钮
            delete_btn = QPushButton("删除")
            delete_btn.setStyleSheet("""
                QPushButton {
                    padding: 3px 8px;
                    background-color: #f56c6c;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                }
                QPushButton:hover {
                    background-color: #f78989;
                }
            """)
            delete_btn.setProperty('script_id', script_id)
            delete_btn.clicked.connect(self.on_delete_script)
            
            # 添加按钮到布局
            btn_layout.addWidget(edit_btn)
            btn_layout.addWidget(start_btn)
            btn_layout.addWidget(log_btn)
            btn_layout.addWidget(delete_btn)
            btn_layout.addStretch()
            
            # 将按钮容器设置到单元格
            self.script_table.setCellWidget(row, 7, btn_widget)
            
        print("表格更新完成")

    def on_delete_script(self):
        """删除脚本按钮点击事件"""
        # 获取发送者（按钮）
        sender = self.sender()
        if not sender:
            return
            
        # 获取脚本ID
        script_id = sender.property('script_id')
        if not script_id:
            return
            
        # 显示确认对话框
        confirm_dialog = QMessageBox(self)
        confirm_dialog.setWindowTitle("提示")
        confirm_dialog.setText("确认要删除此脚本吗？")
        confirm_dialog.setIcon(QMessageBox.Icon.Warning)
        
        # 设置按钮
        confirm_dialog.setStandardButtons(
            QMessageBox.StandardButton.Cancel | 
            QMessageBox.StandardButton.Ok
        )
        confirm_button = confirm_dialog.button(QMessageBox.StandardButton.Ok)
        confirm_button.setText('确定')
        cancel_button = confirm_dialog.button(QMessageBox.StandardButton.Cancel)
        cancel_button.setText('取消')
        
        # 显示对话框
        if confirm_dialog.exec() == QMessageBox.StandardButton.Ok:
            try:
                print(f"开始删除脚本，ID: {script_id}")
                
                # 1. 删除脚本任务关联
                print("删除脚本任务关联")
                self.script_task_manager.delete_by_script_id(script_id)
                
                # 2. 删除脚本扫货账号关联
                print("删除脚本扫货账号关联")
                self.script_scan_account_manager.delete_by_script_id(script_id)
                
                # 3. 删除脚本
                print("删除脚本")
                self.script_manager.delete_script(script_id)
                
                print("删除完成，刷新表格")
                # 刷新表格
                self.refresh_table()
                
            except Exception as e:
                import traceback
                error_msg = f"删除失败: {str(e)}\n{traceback.format_exc()}"
                print(f"错误: {error_msg}")
                QMessageBox.critical(self, "错误", error_msg)

    def on_edit_script(self):
        """编辑脚本按钮点击事件"""
        # 获取发送者（按钮）
        sender = self.sender()
        if not sender:
            return
            
        # 获取脚本ID
        script_id = sender.property('script_id')
        if not script_id:
            return
            
        try:
            print(f"编辑脚本，ID: {script_id}")
            dialog = ScriptDialog(self, script_id)
            dialog.exec()
        except Exception as e:
            import traceback
            error_msg = f"打开编辑对话框失败: {str(e)}\n{traceback.format_exc()}"
            print(f"错误: {error_msg}")
            QMessageBox.critical(self, "错误", error_msg)

    def get_button_row(self, button: QPushButton) -> int:
        """获取按钮所在的表格行
        
        Args:
            button: 按钮对象
            
        Returns:
            int: 按钮所在的行号，如果未找到返回 None
        """
        # 遍历表格的每一行
        for row in range(self.script_table.rowCount()):
            # 获取最后一列（操作列）的单元格
            cell_widget = self.script_table.cellWidget(row, self.script_table.columnCount() - 1)
            if cell_widget:
                # 遍历操作列中的所有按钮
                for child in cell_widget.findChildren(QPushButton):
                    if child is button:
                        return row
        return None

    def on_start_script(self):
        """启动/停止脚本按钮点击事件"""
        try:
            print("开始处理启动/停止脚本事件")
            # 获取发送者（按钮）
            button = self.sender()
            if not button:
                print("未找到发送者按钮")
                return
                
            print(f"按钮文本: {button.text()}")
                
            # 获取按钮所在行
            row = self.get_button_row(button)
            if row is None:
                print("未找到按钮所在行")
                return
            print(f"按钮所在行: {row}")
                
            # 获取脚本ID和当前运行状态
            script_id = button.property('script_id')
            run_status = button.property('run_status')
            print(f"脚本ID: {script_id}, 当前运行状态: {run_status}")
            
            # 获取脚本处理器单例
            processor = ScriptTaskProcessor()
            
            if run_status == 1:  # 如果正在运行，则停止
                print("准备停止脚本...")
                # 停止处理器
                processor.stop()
                print("处理器停止命令已发送")
                    
                # 更新数据库状态
                print("更新数据库运行状态为停止")
                self.script_manager.update_run_status(script_id, 0)  # 0表示停止
                
                # 更新按钮状态
                print("更新按钮状态为停止")
                self.update_script_button_status(script_id, False)
                
                # 更新内部状态
                if script_id in self.running_scripts:
                    print(f"从运行列表中移除脚本 {script_id}")
                    self.running_scripts.remove(script_id)
                print("脚本停止完成")
                    
            else:  # 如果未运行，则启动
                print("准备启动脚本...")
                
                # 打开扫货模式选择对话框
                dialog = ScanModeDialog(self)
                # 连接模式选择信号
                dialog.mode_selected.connect(lambda mode: self.start_script_with_mode(script_id, mode))
                # 显示对话框
                dialog.exec()
                
        except Exception as e:
            import traceback
            error_msg = f"操作脚本失败: {str(e)}\n{traceback.format_exc()}"
            print(f"错误: {error_msg}")
            QMessageBox.critical(self, "错误", error_msg)
            
    def start_script_with_mode(self, script_id, scan_mode):
        """根据选择的模式启动脚本
        
        Args:
            script_id: 脚本ID
            scan_mode: 扫货模式，ScanMode.DYNAMIC 或 ScanMode.POLLING
        """
        try:
            print(f"使用模式 {scan_mode} 启动脚本 {script_id}")
            
            # 获取脚本处理器单例
            processor = ScriptTaskProcessor()
            
            # 启动脚本，传入扫货模式
            mode_name = "动态扫货" if scan_mode is ScanMode.DYNAMIC else "轮询扫货"
            print(f"开始启动脚本，模式: {mode_name}")
            # 设置轮询间隔为5秒（仅在轮询模式下有效）
            interval = 5 if scan_mode is ScanMode.POLLING else 1
            
            # 先启动脚本，确保处理器和扫描器已经初始化
            processor.start(script_id, interval=interval, scan_mode=scan_mode)
            
            # 更新数据库状态
            print("更新数据库运行状态为运行")
            self.script_manager.update_run_status(script_id, 1)  # 1表示运行
            
            # 更新按钮状态
            print("更新按钮状态为运行")
            self.update_script_button_status(script_id, True)
            
            # 更新内部状态
            print(f"将脚本 {script_id} 添加到运行列表")
            self.running_scripts.add(script_id)
            
            # 在脚本启动后创建或显示日志窗口
            if script_id not in self.log_windows or self.log_windows[script_id].isHidden():
                print("创建新的日志窗口")
                # 获取脚本信息
                script = self.script_manager.get_script_by_id(script_id)
                if not script:
                    print(f"脚本 {script_id} 不存在")
                    return
                    
                script_name = script.get('name', '')
                log_window = LogWindow(parent=self, script_id=script_id, script_name=script_name)
                self.log_windows[script_id] = log_window
                
                # 获取脚本运行器并连接信号
                script_runner = get_script_runner()
                log_window.connect_signal_source(script_runner)
                
                # 连接处理器和扫描器的信号
                log_window.connect_signal_source(processor)
                if processor.scanner:
                    log_window.connect_signal_source(processor.scanner)
                
                # 添加初始日志
                log_window.append_log(f"使用扫货模式: {mode_name}")
                log_window.append_log(f"使用脚本实际的ID编号: {script_id}")
                log_window.append_log(f"开始处理脚本 {script_id} 的任务, 处理间隔 {interval} 秒")
                
                # 显示日志窗口
                log_window.show()
            else:
                print("连接已有日志窗口信号")
                log_window = self.log_windows[script_id]
                log_window.connect_signal_source(processor)
                if processor.scanner:
                    log_window.connect_signal_source(processor.scanner)
                
                # 添加初始日志
                log_window.append_log(f"使用扫货模式: {mode_name}")
                log_window.append_log(f"使用脚本实际的ID编号: {script_id}")
                log_window.append_log(f"开始处理脚本 {script_id} 的任务, 处理间隔 {interval} 秒")
                
                log_window.show()
                
            print("脚本启动完成")
            
        except Exception as e:
            import traceback
            error_msg = f"启动脚本失败: {str(e)}\n{traceback.format_exc()}"
            print(f"错误: {error_msg}")
            QMessageBox.critical(self, "错误", error_msg)

    def _handle_script_stop(self, script_id: int):
        """处理脚本停止的UI更新
        
        Args:
            script_id: 脚本ID
        """
        try:
            self.script_manager.update_run_status(script_id, 0)  # 0表示停止
            self.running_scripts.remove(script_id)
            # 更新按钮状态
            self.update_script_button_status(script_id, False)
            # 刷新列表
            self.load_scripts()
        except Exception as e:
            print(f"处理脚本停止失败: {str(e)}")
            
    def update_script_button_status(self, script_id: int, is_running: bool):
        """更新脚本按钮状态
        
        Args:
            script_id: 脚本ID
            is_running: 是否正在运行
        """
        print(f"更新脚本 {script_id} 的按钮状态，运行状态: {is_running}")
        # 遍历表格找到对应的按钮
        for row in range(self.script_table.rowCount()):
            btn_widget = self.script_table.cellWidget(row, self.script_table.columnCount() - 1)
            if not btn_widget:
                continue
                
            # 获取启动按钮
            start_btn = None
            for child in btn_widget.children():
                if isinstance(child, QPushButton) and child.property('script_id') == script_id:
                    if child.text() in ["启动", "停止"]:
                        start_btn = child
                        break
                        
            if start_btn:
                print(f"找到按钮，当前文本: {start_btn.text()}")
                # 更新按钮状态
                if is_running:
                    start_btn.setText("停止")
                    start_btn.setStyleSheet("""
                        QPushButton {
                            padding: 3px 8px;
                            background-color: #f56c6c;
                            color: white;
                            border: none;
                            border-radius: 2px;
                            font-size: 12px;
                        }
                        QPushButton:hover {
                            background-color: #f78989;
                        }
                    """)
                    # 更新运行状态属性
                    start_btn.setProperty('run_status', 1)
                else:
                    start_btn.setText("启动")
                    start_btn.setStyleSheet("""
                        QPushButton {
                            padding: 3px 8px;
                            background-color: #67c23a;
                            color: white;
                            border: none;
                            border-radius: 2px;
                            font-size: 12px;
                        }
                        QPushButton:hover {
                            background-color: #85ce61;
                        }
                    """)
                    # 更新运行状态属性
                    start_btn.setProperty('run_status', 0)
                print(f"按钮状态已更新，新文本: {start_btn.text()}, 新运行状态: {start_btn.property('run_status')}")
                break

    def on_view_scan_log(self):
        """查看扫货日志按钮点击事件"""
        try:
            # 获取发送者（按钮）
            button = self.sender()
            if not button:
                return
                
            # 获取按钮所在行
            row = self.get_button_row(button)
            if row is None:
                return
                
            # 获取脚本ID
            script_id = button.property('script_id')
            if not script_id:
                return
                
            # 获取脚本信息
            script = self.script_manager.get_script_by_id(script_id)
            if not script:
                print(f"脚本 {script_id} 不存在")
                return
                
            script_name = script.get('name', '')
                
            # 如果日志窗口已存在且未关闭，则显示它
            if script_id in self.log_windows and not self.log_windows[script_id].isHidden():
                self.log_windows[script_id].activateWindow()
                return
                
            # 创建新的日志窗口
            log_window = LogWindow(parent=self, script_id=script_id, script_name=script_name)
            self.log_windows[script_id] = log_window
            
            # 获取脚本运行器并连接信号
            script_runner = get_script_runner()
            log_window.connect_signal_source(script_runner)
            
            # 获取处理器实例并连接信号，无论脚本是否正在运行
            processor = ScriptTaskProcessor()
            log_window.connect_signal_source(processor)
            
            # 如果处理器有扫描器，也连接扫描器的信号
            if processor.scanner:
                log_window.connect_signal_source(processor.scanner)
            
            # 添加初始日志信息
            log_window.append_log(f"查看脚本 {script_id} ({script_name}) 的日志")
            
            # 如果脚本正在运行，确保连接到正在运行的处理器和扫描器
            if script_id in script_runner.running_processors:
                running_processor = script_runner.running_processors[script_id]
                log_window.connect_signal_source(running_processor)
                if running_processor.scanner:
                    log_window.connect_signal_source(running_processor.scanner)
                log_window.append_log("脚本当前正在运行中...")
            else:
                log_window.append_log("脚本当前未运行")
            
            # 显示日志窗口
            log_window.exec()
            
        except Exception as e:
            print(f"打开日志窗口失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"打开日志窗口失败: {str(e)}")
